package com.yuanfeng.userms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.aspect.UserPermissionsResult;
import com.yuanfeng.commoms.aspect.UserService;
import com.yuanfeng.commoms.config.PermissionsConstant;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.PasswordUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.userms.dto.UserSellerBaseDTO;
import com.yuanfeng.userms.entity.UserSellerBaseEntity;
import com.yuanfeng.userms.mapper.UserSellerBaseMapper;
import com.yuanfeng.userms.service.UserInfoService;
import com.yuanfeng.userms.service.UserSellerBaseService;
import com.yuanfeng.userms.vo.UserSellerBaseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class UserSellerBaseServiceImpl extends ServiceImpl<UserSellerBaseMapper, UserSellerBaseEntity>
    implements UserSellerBaseService{

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public ResponseResult getSellerInfo(Map<String, String> returnMap) {
        UserSellerBaseEntity ucenterSellerBaseEntity = this.baseMapper.selectOne(new LambdaQueryWrapper<UserSellerBaseEntity>()
                .eq(UserSellerBaseEntity::getShopId, returnMap.get("shopId"))
                .eq(UserSellerBaseEntity::getSellerIsAdmin, CommonType.commonStatus.YES.getCode()));
        return ResponseResult.success(ucenterSellerBaseEntity);
    }

    @Override
    public ResponseResult add(UserSellerBaseDTO userSellerBase) {
        String token = userSellerBase.getToken();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (null == userInfo.getShopId()) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SELLER_ACCOUNT, token);
        if (!userPermissionsResult.getFlag()) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        //获取shopId
        String shopId = userInfo.getShopId();
        //判断是否为品牌店铺
        Map<String, String> paraMap1 = new HashMap<>();
        paraMap1.put("shopId", shopId);
        UserSellerBaseEntity entity = this.baseMapper.selectOne(new LambdaQueryWrapper<UserSellerBaseEntity>()
                .eq(UserSellerBaseEntity::getShopId, shopId)
                .eq(UserSellerBaseEntity::getSellerIsAdmin, CommonType.commonStatus.YES.getCode()));
        if (entity != null) {

            UserInfoVO toAddUserInfo = null;
            Integer num = 0;
            if (entity.getShopType() == 3) {
                //走品牌查询
                toAddUserInfo = userInfoService.getUserInfoByPhoneNumber1(userSellerBase.getUserMobile(), shopId);

                //判断该手机号是否已被其他的商家绑为子账号
                num = this.baseMapper.selectCount(new LambdaQueryWrapper<UserSellerBaseEntity>()
                        .eq(UserSellerBaseEntity::getSellerName, userSellerBase.getUserMobile())
                        .eq(UserSellerBaseEntity::getShopType, CommonType.ShopType.BRAND_SHOP.getCode())
                        .eq(UserSellerBaseEntity::getShopId, shopId));
                if (null == toAddUserInfo) {
                    toAddUserInfo = userInfoService.getUserInfoByMobile(userSellerBase.getUserMobile());
                }
            } else {
                toAddUserInfo = userInfoService.getUserInfoByMobile(userSellerBase.getUserMobile());

                //判断该手机号是否已被其他的商家绑为子账号
                QueryWrapper<UserSellerBaseEntity> objectQueryWrapper = new QueryWrapper<>();
                objectQueryWrapper.eq("seller_name", userSellerBase.getUserMobile());
                num = this.baseMapper.selectCount(objectQueryWrapper);
            }
            if (null == toAddUserInfo) {
                return ResponseResult.fail(2, "用户未注册");
            }
            if (0 != num) {
                return ResponseResult.fail(2, "该账号已被绑定");
            } else {
                Integer count = this.baseMapper.selectShopGateCount(userSellerBase.getUserMobile());
                if(count > 0){
                    return ResponseResult.fail(2, "该账号已被绑定");
                }
            }
            String paramPasswordString = toAddUserInfo.getPassword();
            if (!PasswordUtils.BCryptPasswordMatches(userSellerBase.getPassword(),paramPasswordString)) {
                return ResponseResult.fail(2, "账号或者密码错误");
            }
            if (null == userInfo.getShopId()) {
                return ResponseResult.fail(2, "ShopId为null");
            }
            UserSellerBaseEntity baseEntity = new UserSellerBaseEntity();
            baseEntity.setSellerName(toAddUserInfo.getUserName());
            baseEntity.setShopId(Integer.valueOf(userInfo.getShopId()));
            baseEntity.setUserId(toAddUserInfo.getUserId());
            baseEntity.setRightsGroupId(userSellerBase.getGroupId());
            baseEntity.setSellerIsAdmin((byte) 0);
            baseEntity.setSellerLoginTime(new Date());
            baseEntity.setSellerGroupId(userSellerBase.getGroupId());
            baseEntity.setShopType(userSellerBase.getShopType());
            Integer torfInteger = this.baseMapper.insert(baseEntity);
            if (1 == torfInteger) {
                return ResponseResult.success(1, "添加账户成功");
            }

        }
        return ResponseResult.fail(2, "添加账户失败");
    }

    @Override
    public ResponseResult get(Map<String, String> paraMap) {
        String token = paraMap.get("token");
        UserInfoVO userInfo =ParseTokenUtils.getUserInfoByToken(token);
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, token);
        if (!userPermissionsResult.getFlag()) {
            return ResponseResult.fail(10086, "没有权限");
        }
        paraMap.put("shopId", userInfo.getShopId());
        List<UserSellerBaseDTO> list = this.baseMapper.getSellerAccount(paraMap);
        if (null != list) {
            return ResponseResult.success(list);
        }
        return ResponseResult.fail(2, "查询账号失败");
    }

    @Override
    public ResponseResult delete(Map<String, String> paraMap) {
        String token = paraMap.get("token");
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, token);
        if (!userPermissionsResult.getFlag()) {
            return ResponseResult.fail(10086, "没有权限");
        }
        QueryWrapper<UserSellerBaseEntity> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("seller_id",paraMap.get("sellerId"));
        Integer torfInteger = this.baseMapper.delete(objectQueryWrapper);
        if (1 == torfInteger) {
            return ResponseResult.success(1, "删除账号成功");
        }
        return ResponseResult.fail(2, "删除账号失败");
    }

    @Override
    public ResponseResult update(Map<String, String> paraMap) {
        String token = paraMap.get("token");
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, token);
        if (!userPermissionsResult.getFlag()) {
            return ResponseResult.fail(10086, "没有权限");
        }
        UserSellerBaseEntity baseEntity = new UserSellerBaseEntity();
        baseEntity.setSellerId(paraMap.get("sellerId"));
        baseEntity.setSellerGroupId(Integer.valueOf(paraMap.get("sellerGroupId")));
        Integer returnTorf = this.baseMapper.updateById(baseEntity);
        if (1 == returnTorf) {
            return ResponseResult.success(1, "修改权限成功");
        }
        return ResponseResult.fail(2, "修改失败");
    }

    @Override
    public List<UserSellerBaseVO> getSellerBase(Integer shopId) {
        List<UserSellerBaseVO> list = this.baseMapper.getSellerBase(shopId);
        return list;
    }
}
